#!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-
import sys,os,time
import requests
import urllib2
import urllib
import base64
import json
import ConfigParser

product_config = "product_version.conf"

def get_common_config(items):
    product_offering = product_version = product_operator = static_token = ""
    for item in items:
        if item[0] == "product_offering":
            product_offering = item[1]
        elif item[0] == "product_version":
            product_version = item[1]
        elif item[0] == "product_operator":
            product_operator = item[1]
        elif item[0] == "static_token":
            static_token = item[1]
        #print item[0],item[1]
    return (static_token, product_offering, product_version, product_operator)

    
cf = ConfigParser.ConfigParser()
cf.read(product_config)
image_list = cf.sections()
#print projects_list
static_token, product_offering, product_version, product_operator = get_common_config(cf.items("versoninfo_config"))
images = [] #初始化镜像信息列表

#print static_token,product_offering,product_version,product_operator
image_list.remove("versoninfo_config")
for image in image_list:
    imageid, imagename,imagestatus = image.split('/')
    dict={}
    dict['imageId']=imageid
    dict['imageName']=imagename
    dict['imageStatus']='Success'
    images.append(dict)

#获取动态token；
def get_dynamic_token(str,apptoken_static):    
    apptoken=apptoken_static
    #print apptoken
    apptoken_en=base64.b64encode(apptoken)#使用base64编码
    #参考资料http://3ms.huawei.com/hi/group/2692001/wiki_5020167.html#2
    url="http://w3cloud.huawei.com/ApiCommonQuery/appToken/getRestAppDynamicToken"
    values={'appId':'com.huawei.env_test',
            'credential':apptoken_en
            }
    json_str=json.dumps(values)
    headers={'Content-Type':'application/json'}
    #print values
    try:
        res=requests.post(url,data=json_str,headers=headers)
        print res.text
        html=res.text
        hjson=json.loads(html)
        dynamictoken=hjson["result"]
        return dynamictoken
    except requests.RequestException as e:
        current_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        info=current_time+":"+str(e)+"\n"
        with open("Error_log.txt","a") as f:
            f.write(info)

str1=""
apptoken_static=static_token#在api center注册应用后的静态token
token_dynamic =get_dynamic_token(str1,apptoken_static)#获取动态token；
#print token_dynamic
#将镜像写入到CMC        
#url_cmc="http://10.22.37.84:9080/cmc/api/v3.0/createSnapshotInfo"#CMC测试环境创建镜像接口
url_cmc="http://es.cmc.huawei.com:9080/cmc/api/v3.0/createSnapshotInfo" #CMC生产环境创建镜像接口

values={'product':product_offering,#配置产品
        'name':product_version,#配置版本
        'createdBy':product_operator,
        'serviceName':'Product_version',
        'versionImage':images #hicloud的镜像信息，如果多个镜像就添加多行
        }
json_str=json.dumps(values)
headers={'Content-Type':'application/json',
        'Authorization':token_dynamic}

try:
    res=requests.post(url_cmc,data=json_str,headers=headers)
    print res.text
    current_time1=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    info1=current_time1+":"+res.text+"\n"
    #with open("create_image_log.txt","a") as f1:
    #    f1.write(info1)
    print res.raise_for_status()
except requests.RequestException as e:
    current_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    info=current_time+":"+res.text+"\n"
    with open("create_image_log_Error_log.txt","a") as f:
        f.write(info) 
